import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';

export default defineConfig(({ mode }) => {
  const isLib = mode === 'lib';

  return {
    plugins: [vue()],
    build: isLib
      ? {
          lib: {
            entry: './src/main.ts',
            name: 'MenuIconComponents',
            fileName: 'index',
            formats: ['es'],
          },
          rollupOptions: {
            external: ['vue'],
            output: {
              globals: {
                vue: 'Vue',
              },
              exports: 'named',
              // 确保图标库被正确内联
              inlineDynamicImports: true,
              // 优化文件命名和目录结构
              assetFileNames: (assetInfo) => {
                if (!assetInfo.name) return 'assets/[name].[hash][extname]';
                const info = assetInfo.name.split('.');
                const ext = info[info.length - 1];
                if (/\.(css)$/.test(assetInfo.name)) {
                  return `assets/css/index.[hash][extname]`;
                }
                return `assets/[name].[hash][extname]`;
              },
              chunkFileNames: (chunkInfo) => {
                const facadeModuleId = chunkInfo.facadeModuleId
                  ? chunkInfo.facadeModuleId
                      .split('/')
                      .pop()
                      ?.replace('.vue', '') || 'chunk'
                  : 'chunk';
                return `components/${facadeModuleId}.[hash].mjs`;
              },
              entryFileNames: 'index.mjs',
            },
          },
          // 确保 CSS 文件被包含在构建中
          cssCodeSplit: false,
          outDir: 'dist',
          sourcemap: true,
        }
      : {
          outDir: 'dist',
          sourcemap: true,
        },
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
  };
});
